/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.acme.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author iiping
 */
public class Tbl2Operations extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

      String transition = request.getRequestURI();

      if(transition.equals("/table2/getresults")){
        getResults(request, response);
      } else if ( transition.equals("/table2/update")){
        update(request, response);
      } else if (transition.equals("/table2/delete")){
        delete(request, response);
      } else if (transition.equals("/table2/insert")){
        insert(request, response);
      } else{
        RequestDispatcher rd = request.getRequestDispatcher("/views/UnAuthResp.jsp");
        rd.forward(request, response);
      }

    }


    //transitions()

    protected void getResults(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        DAOCentral ds = DAOCentral.getInstance();
        HashSet<TOTable2> results  ;
        response.setContentType("text/plain;utf-8");
        PrintWriter out = response.getWriter();

        int route = 0;
        HashSet<Integer> keys = new HashSet<Integer>();

        //table1/getresults
        //test if key or keys
        if(request.getParameter("key") != null){ // 2
          //now evaluate if key is ok
          String strK = request.getParameter("key");
          try{
            int tmpK = Integer.parseInt(strK);

            if(strK != null && tmpK > 0){
              keys.add(Integer.valueOf(tmpK));
              route = 2;
            }
          }
          catch(RuntimeException e){
            route  = 0;
          }

        } else if(request.getParameter("keys") != null){ // 1
          String strks = request.getParameter("keys");
          String[] strK = null;
          //bug remover

          try{
            strks = URLEncoder.encode(strks, "UTF-8");
            strK = strks.split("\\+");



                  //lets just check if all are valid integers and is greater than 0
                  //since we do this we will just add it directly to keys
                  for(int i=0; strK.length > i ; i++){
                    try{
                      int kVal = Integer.parseInt(strK[i]);
                      keys.add(Integer.valueOf(kVal));
                    }
                    catch(RuntimeException e){

                      route  = 0;
                    }
                    route = 2;
                  }


                  route =1 ;



          }
          catch(UnsupportedEncodingException ex){
            route  = 0;
          }


        } else{ // 0
         //and do nothing
        }

        switch(route){
          case 2:
          case 1:
            results = ds.retTOTable2(((Integer[]) keys.toArray(new Integer[0])) );
            break;
          case 0:
          default:
            results  = new HashSet<TOTable2>();
            break;
        }

        genericResponse(results, response);

    }

    protected void update(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      // validate all inputs
      String key = request.getParameter("key");
      String newValue = request.getParameter("newValue");
      String result = "updateFailed";
      if(null != key && null != newValue){
        try{
          key = URLEncoder.encode(key, "UTF-8");
          newValue = URLEncoder.encode(newValue, "UTF-8");

          // now pass the integer just to be valid
          Integer iKey = new Integer(Integer.parseInt(key));
          Integer iNewValue = new Integer(Integer.parseInt(newValue));

          TOTable2 tbl2 = new TOTable2(iKey, iNewValue);

          DAOCentral.getInstance().updateTOTbl2Key(tbl2);
          result = "udpated";
        }
        catch(NumberFormatException e){

        }
      }
      genericResponse(result, response);


    }

    protected void delete(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      // validate all inputs
      String key = request.getParameter("key");
      String result = "deleteFailed";
      if(null != key){
        try{
          key = URLEncoder.encode(key, "UTF-8");

          // now pass the integer just to be valid
          Integer iKey = new Integer(Integer.parseInt(key));

          DAOCentral.getInstance().deleteTOTbl2Key(iKey);
          result = "deleted";
        }
        catch(NumberFormatException e){

        }
      }
      genericResponse(result, response);
    }

    protected void insert(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      // validate all inputs
      String key = request.getParameter("key");
      String newValue = request.getParameter("newValue");
      String result = "insertFailed";
      if(null != key && null != newValue){
        try{
          key = URLEncoder.encode(key, "UTF-8");
          newValue = URLEncoder.encode(newValue, "UTF-8");

          // now pass the integer just to be valid
          Integer iKey = new Integer(Integer.parseInt(key));
          Integer iNewValue = new Integer(Integer.parseInt(newValue));

          TOTable2 tbl2 = new TOTable2(iKey, iNewValue);

          DAOCentral.getInstance().create(tbl2);
          result = "inserted";
        }
        catch(NumberFormatException e){

        }
      }
      genericResponse(result, response);
    }

    private void genericResponse(HashSet<TOTable2> results, HttpServletResponse response)
    throws ServletException, IOException {

      PrintWriter out = response.getWriter();
      try{
        out.write("{"); // begin of dataset
        int c = 0;
        for(TOTable2 result : results){
          if(c > 0)
            out.write(",");
          out.write(result.toString());
          c++;
        }
        out.write("}"); //end of dataset
      }
      finally{
        out.close();
      }
    }

    private void genericResponse(String result, HttpServletResponse response)
    throws ServletException, IOException {

      PrintWriter out = response.getWriter();
      try{
        out.write("{"); // begin of dataset
        out.write(result);
        out.write("}"); //end of dataset
      }
      finally{
        out.close();
      }
    }



    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
